<template>
  <div>
    <div style="display: flex; justify-content: space-around; align-items: center">
      <span></span>
      <el-dropdown @command="selectType">
        <el-button type="primary" v-text="typeName" style="width: 100px">
          <i class="el-icon-arrow-down el-icon--right"></i>
        </el-button>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command="全部类型">全部类型</el-dropdown-item>
          <el-dropdown-item v-for="i in typeData" :key="i.id" :command="i.typeName">{{i.typeName}}</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
      <h3>菜品列表</h3>
      <div style="width: 300px">
        <el-input placeholder="根据菜品名称或菜品类型搜索" v-model="inputValue" @keyup.enter="search">
          <el-button slot="append" icon="el-icon-search" @click="search()"></el-button>
        </el-input>
      </div>
      <el-button type="primary" @click="resetting">重置</el-button>
    </div>
    <el-table class="table" :data="dishData" style="width: 100%">
      <el-table-column prop="photo" label="图片"  align="center">
        <template slot-scope="scope">
          <el-image :src="url + scope.row.photo"  style="width: 100px"/>
        </template>
      </el-table-column>
      <el-table-column prop="dishName" label="名称"  align="center"></el-table-column>
      <el-table-column prop="typeName" label="类型" align="center"></el-table-column>
      <el-table-column prop="price" sortable label="价格" align="center">
        <template slot-scope="scope">
          <span>{{scope.row.price / 100}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="grade" sortable label="评分" align="center">
        <template slot-scope="scope">
          <div class="block">
            <el-rate
              v-model="scope.row.grade"
              disabled
              show-score
              text-color="#ff9900"
              score-template="{value}" v-if="scope.row.grade != null">
            </el-rate>
            <div v-if="scope.row.grade == null">暂无评分</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center">
        <template slot-scope="scope">
          <el-checkbox v-on:change="selectDish(scope.row)" style="margin-right: 10px" v-bind:value="check(scope.row.id)"></el-checkbox>
          <el-button @click="getAssessData(scope.row.id)" type="text">
            查看评论
          </el-button>
          <el-drawer
            title="菜品评论"
            :visible.sync="assess"
            size="40%"
            style="font-size: 15px">
            <el-divider></el-divider>
            <div v-for="i in assessData">
              <div style="display: flex; justify-content: left; color: black">
                <div style="width: 20%">
                  <img :src="url + i.photo" alt="" style="width: 60px; border-radius: 50%; margin-top: 10px">
                </div>
                <div style="width: 75%; text-align: left">
                  <h2 style="display: block">{{i.username}}</h2>
                  <p>{{i.content}}</p>
                  <div style="display: flex; justify-content: space-between">
                    <div class="block">
                      <el-rate
                        v-model="i.grade"
                        disabled
                        show-score
                        text-color="#ff9900"
                        score-template="{value}">
                      </el-rate>
                    </div>
                    <span style="margin-right: 40px">{{i.time}}</span>
                  </div>
                </div>
              </div>
              <el-divider></el-divider>
            </div>
          </el-drawer>
        </template>
      </el-table-column>
    </el-table>
    <el-badge :value="count" class="cart" >
      <el-button @click="shopping_cart = true" type="primary" icon="el-icon-shopping-cart-2" circle>
        <el-drawer
          :title="'已选：' + count + ' 道 ' + ' 合计：' + totalPrice / 100 + ' 元'"
          :direction="'btt'"
          :append-to-body="true"
          :visible.sync="shopping_cart"
          size="60%"
          style="font-size: 15px">
            <div style="display: flex; align-items: center; margin-left: 20px">
              <span>备注：</span>
              <el-input
                type="textarea"
                placeholder="请输入内容"
                v-model="notes"
                maxlength="100"
                style="width: 400px"
                show-word-limit>
              </el-input>
            </div>
            <el-table class="table" :data="selectDishList" style="width: 90%">
              <el-table-column prop="photo" label="图片" align="center">
                <template slot-scope="scope">
                  <el-image :src="url + scope.row.photo"  style="width: 100px"/>
                </template>
              </el-table-column>
              <el-table-column prop="dishName" label="名称" align="center"></el-table-column>
              <el-table-column prop="price" sortable label="价格" align="center">
                <template slot-scope="scope">
                  <span>{{scope.row.price / 100}}</span>
                </template>
              </el-table-column>
              <el-table-column prop="grade" sortable label="评分" align="center">
                <template slot-scope="scope">
                  <div class="block">
                    <el-rate
                      v-model="scope.row.grade"
                      disabled
                      show-score
                      text-color="#ff9900"
                      score-template="{value}" v-if="scope.row.grade != null">
                    </el-rate>
                    <div v-if="scope.row.grade == null">暂无评分</div>
                  </div>
                </template>
              </el-table-column>
            </el-table>
          <el-row justify="ending">
            <el-button class="cart" @click="order()" size="small" type="primary" icon="el-icon-shopping-cart-2">结算</el-button>
          </el-row>
        </el-drawer>
      </el-button>
    </el-badge>
    <el-button-group>
      <el-button type="primary" @click="firstPage">首页</el-button>
      <el-button type="primary" icon="el-icon-arrow-left" @click="beforePage">上一页</el-button>
      <el-button type="primary" @click="nextPage">下一页<i class="el-icon-arrow-right el-icon--right"></i></el-button>
      <el-button type="primary" @click="lastPage">尾页</el-button>
    </el-button-group>
  </div>
</template>

<script>

export default {
  name: 'CustomerDish',
  data () {
    return {
      dishData: [],
      typeData: [],
      assessData: [],
      assess: false,
      shopping_cart: false,
      selectDishMap: new Map(),
      selectDishList: [],
      selectDishIdSet: new Set(),
      selectDishIdList: [],
      count: 0,
      totalPrice: 0,
      notes: '',
      inputValue: '',
      typeName: "全部类型",
      url: this.$url,
      pIndex: 1,
      pSize: 6,
      pCount: 1
    }
  },
  mounted () {
    if (sessionStorage.getItem('phone') !== null) {
      this.getDishData()
      this.getTypeData()
    }
  },
  methods: {
    firstPage() {
      if (this.pIndex <= 1) {
        this.$message.error("当前已经在首页了！")
      } else {
        this.pIndex = 1;
        this.getDishData();
      }
    },
    beforePage() {
      if (this.pIndex <= 1) {
        this.$message.error("当前已经在首页了！")
      } else {
        this.pIndex -= 1;
        this.getDishData();
      }
    },
    nextPage() {
      if (this.pIndex >= this.pCount) {
        this.$message.error("当前已经在末页了！");
      } else {
        this.pIndex = parseInt(this.pIndex) + 1;
        this.getDishData();
      }
    },
    lastPage() {
      if (this.pIndex >= this.pCount) {
        this.$message.error("当前已经在末页了！");
      } else {
        this.pIndex = this.pCount;
        this.getDishData();
      }
    },
    resetting () {
      this.typeName = '全部类型'
      this.inputValue = ''
      this.search()
      this.selectDishMap.clear()
      this.selectDishList = []
      this.selectDishIdSet.clear()
      this.selectDishIdList = []
      this.totalPrice = 0
      this.count = 0
    },
    selectType (command) {
      // 根据类型筛选
      this.typeName = command
      this.search()
    },
    search() {
      // 获取菜品列表，这个是修改了筛选参数，需要重置页数
      this.pIndex = 1;
      let tmp1 = this.typeName
      let tmp2 = this.inputValue
      if (tmp1 === '全部类型') {
        tmp1 = null
      }
      if (tmp2 === '') {
        tmp2 = null
      }
      // 用户根据类型筛选和搜索框，获取菜品列表
      this.$request.post('/dish/getlist', {
        "typeName": tmp1,
        "inputValue": tmp2,
        'pIndex': this.pIndex,
        'pSize': this.pSize
      }).then((result) => {
        if (result.code === 200) {
          this.dishData = result.data.dishList
          this.pCount = result.data.pageCount
        } else {
          this.$message.error('获取菜品列表失败！');
        }
      })
    },
    getDishData () {
      // 获取菜品列表，不需要重置页数
      let tmp1 = this.typeName
      let tmp2 = this.inputValue
      if (tmp1 === '全部类型') {
        tmp1 = null
      }
      if (tmp2 === '') {
        tmp2 = null
      }
      this.$request.post(
        '/dish/getlist', {
          "typeName": tmp1,
          "inputValue": tmp2,
          'pIndex': this.pIndex,
          'pSize': this.pSize
        }).then((result) => {
        if (result.code === 200) {
          this.dishData = result.data.dishList
          this.pCount = result.data.pageCount
        } else {
          this.$message.error('获取菜品列表失败！');
        }
      })
    },
    getTypeData () {
      // 获取菜品类型列表
      this.$request.get('/type/getlist').then((result) => {
        if (result.code === 200) {
          this.typeData = result.data
        } else {
          athis.$message.error('获取菜品类型失败！');
        }
      })
    },
    selectDish (dish) {
      // 用户点击复选框，更新选择的菜品数组
      if (this.selectDishMap.has(dish.id)) {
        // 取消勾选
        this.selectDishIdSet.delete(dish.id)
        this.selectDishMap.delete(dish.id)
        this.totalPrice -= dish.price
      } else {
        // 勾选
        this.selectDishIdSet.add(dish.id)
        this.selectDishMap.set(dish.id, dish)
        this.totalPrice += dish.price
      }
      // 更新已选菜品数
      this.count = this.selectDishIdSet.size
      // 更新选中的 菜品ID数组
      this.selectDishIdList = Array.from(this.selectDishIdSet);
      // 更新选择的 菜品数组
      this.selectDishList = []
      for (let i of this.selectDishIdSet) {
        this.selectDishList.push(this.selectDishMap.get(i))
      }
    },
    check (id) {
      for (let i of this.selectDishIdList) {
        if (i === id) {
          return true;
        }
      }
      return false;
    },
    getAssessData (dishId) {
      // 点击查看评论，获取评论列表
      this.assess = true
      this.$request.post('/assess/getlist', {
        "dishId": dishId
      }).then((result) => {
        if (result.code === 200) {
          this.assessData = result.data
        } else {
          this.$message.error('获取评论列表失败！');
        }
      })
    },
    order () {
      // 用户点击结算
      if (this.selectDishIdList.length === 0) {
        this.$message.error('请选择菜品！');
      } else {
        if (confirm("确定要进行结算？")) {
          this.$request({
            url: '/order/add',
            method: 'post',
            data: {
              'arrDishId': this.selectDishIdList.toString(),
              'notes': this.notes
            }
          }).then(result => {
            if (result.code === 200 && result.data > 0) {
              this.$message.success('下单成功！');
              this.$router.push('/customer/customerOrder')
            } else {
              this.$message.error('下单失败！');
            }
          })
        }
      }
    }
  }
}
</script>

<style scoped>
.table {
  width: 90%;
  font-size: small;
}
.cart{
  position: fixed;
  right: 60px;
  bottom: 50px;
}
</style>
